<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    .top {
        margin-left: 250px;
        margin-top: 20px;
    }
</style>

<body>
    <div class="top">
        按照价格查询：<input type="text" class="star">- <input type="text" class="end"> <button id="search">搜索</button>
        按照商品名称查询： <input type="text" class="priname">
        <button class="nsearch">查询</button>
        <table border>
            <thead>
                <tr>
                    <th>id</th>
                    <th>产品名称</th>
                    <th>产品价格</th>
                </tr>
            </thead>
            <tbody>

            </tbody>
        </table>
    </div>
</body>
<script>
    var data = [
        { id: 1, name: '手机', price: 199 },
        { id: 2, name: '上衣', price: 594 },
        { id: 3, name: '眼镜', price: 182 },
        { id: 4, name: '鞋子', price: 752 },
        { id: 5, name: '裤子', price: 752 },
    ]
    const tbody = document.querySelector('tbody');
    var search = document.getElementById('search')
    const star = document.querySelector('.star')
    const end = document.querySelector('.end')
    const priname = document.querySelector('.priname')
    const nsearch = document.querySelector('.nsearch')
    function setDate(mydata) {
        tbody.innerHTML = '';
        mydata.forEach((value) => {
            const tr = document.createElement('tr')
            tr.innerHTML = '<td style="text-align:center">' + value.id + '</td><td style="text-align:center">' + value.name + '</td><td style="text-align:center">' + value.price + '</td>'
            tbody.appendChild(tr)
        })
    }
    setDate(data)

    // 根据价格查找商品
    search.addEventListener('click', () => {
        var newDate = data.filter((value) => {
            return value.price >= star.value && value.price <= end.value
        })
        setDate(newDate)
    })

    // 根据商品名称查找(模糊查询)
    nsearch.addEventListener('click', () => {
        var nDate = data.filter((value) => {
            return value.name.includes(priname.value)
        })
        setDate(nDate)
    })
    
    // 根据商品名称查找(唯一查询)
    // nsearch.addEventListener('click', () => {
    //     var arr = [];
    //     data.some((value) => {
    //         if (value.name === priname.value) {
    //             arr.push(value)
    //             return true
    //         }
    //     })
    //     setDate(arr)
    // })


</script>

</html>